package com.bwie.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

@Controller
public class LoginController {
	
	//跳转至QQ登录页面
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public void login(HttpServletRequest request,HttpServletResponse response) {

		response.setContentType("text/html;charset=utf-8");
		try {
			response.sendRedirect(new Oauth().getAuthorizeURL(request));
		} catch (IOException | QQConnectException e) {
			e.printStackTrace();
		}
	}
	//跳转
	@RequestMapping("/tologin")
	public String tologin() {
		return "login";
	}
	
//获取用户信息
	@RequestMapping(value="/mylogin")
	public ModelAndView userInfo(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("进来了");
		//设置编码
		response.setContentType("text/html;charset=utf-8");
		try {
			AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
			
			System.out.println("accessTokenObj:-----"+accessTokenObj);
			
			String accessToken = null,openID = null;
			
//			long getExpireln = 0L;
//			getExpireln = accessTokenObj.getExpireIn();
			
			accessToken = accessTokenObj.getAccessToken();

			OpenID OpendidObj = new OpenID(accessToken);
			
			openID = OpendidObj.getUserOpenID();

			UserInfo userInfo = new UserInfo(accessToken, openID);
			UserInfoBean userInfoBean = userInfo.getUserInfo();
			String nickName = userInfoBean.getNickname();
			String sex = userInfoBean.getGender();
			System.out.println(nickName);
			System.out.println(sex);
			ModelAndView mv = new ModelAndView();
			mv.addObject("nickName", nickName);
			mv.addObject("sex", sex);
			mv.setViewName("userinfo");
			
		} catch (QQConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return null;
		
	}
	
	
	
}
